package com.example.skyline.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.skyline.Utils.CipherUtils;
import com.example.skyline.Utils.TokenUtils;
import com.example.skyline.entity.User;
import com.example.skyline.entity.UserRole;
import com.example.skyline.exception.ServiceException;
import com.example.skyline.mapper.UserMapper;
import com.example.skyline.mapper.UserRoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper  userRoleMapper;

    public User login(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());

        if (dbUser == null) {
            throw new ServiceException("500", "用户名或密码错误");
        }

        if (!SecureUtil.md5(user.getPassword() + dbUser.getSalt()).equals(dbUser.getPassword())) {
            throw new ServiceException("500", "用户名或密码错误");
        }

        String token = TokenUtils.createToken(String.valueOf(dbUser.getId()), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }


    public void register(User user) {
        String salt = CipherUtils.salt();

        user.setUsername(createUsername());
        user.setPassword(SecureUtil.md5(user.getPassword() + salt));
        user.setSalt(salt);
        // 默认用户名称
        String uuidPart = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        user.setName("新用户" + uuidPart);

        userMapper.register(user);
    }


    // 10位随机数字账号 --- 第一位不为 0
    private  String createUsername() {
        Random random = new Random();
        String username;
        User dbUser = null;

        do {
            StringBuilder usernameBuilder = new StringBuilder();
            usernameBuilder.append(random.nextInt(9) + 1);

            for (int i = 0; i < 9; i++) {
                usernameBuilder.append(random.nextInt(10));
            }

            username = usernameBuilder.toString();
            dbUser = userMapper.selectByUsername(username);
        } while (dbUser != null);

        return username;
    }


    public PageInfo<User> getUserInfo(Integer pageNum, Integer pageSize, String name, String username) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectAll(name, username);
        return new PageInfo<>(userList);
    }

    public int editUserRole(UserRole userRole) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userRole.getUserId());
        return userRoleMapper.update(userRole, queryWrapper);
    }
}
